package main

import (
	. "MessageParser"
	. "Network"
	"bufio"
	. "fmt"
	"io"
)

func handleRequest(theMessageRequest MessageRequest) MessageResponse {
	Println("[handleRequest] MessageRequest: ", theMessageRequest)

	var aResponse MessageResponse = MessageResponse{
		theMessageRequest.ID,
		theMessageRequest.Type,
		theMessageRequest.Name,
		theMessageRequest.IP,
		theMessageRequest.Port,
		0}

	switch theMessageRequest.Type {
	case 0:
		AddService(theMessageRequest.Name, theMessageRequest.IP, theMessageRequest.Port)
	case 1:
		RemoveService(theMessageRequest.Name, theMessageRequest.IP, theMessageRequest.Port)
	case 2: // Update
		AddService(theMessageRequest.Name, theMessageRequest.IP, theMessageRequest.Port)
	case 3:
		item, err := GetService(theMessageRequest.Name)
		if err != nil {
			Println("[handleRequest] ", err)
			aResponse.ErrorCode = 1
		} else {
			aResponse.IP = item.Hostname
			aResponse.Port = item.Port
		}
	default:
		Println("[handleRequest] Invalid Type.")
	}

	return aResponse
}

func handleConnection(client Client) {
	// Close it when handleConnection is end.
	defer client.Stop()
	Println("[handleConnection] client.IP: ", client.IP)

	bufferReader := bufio.NewReader(client.Conn)

	for {
		str, err := bufferReader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				// close of client
			}
			Println("[handleConnection] ReadString error. ", err)
			client.Stop()
			return
		}

		aMessageRequest, err := SerializationOfMessageRequest(str)
		if err != nil {
			Println("[handleConnection] SerializationOfMessageRequest error. ", err)
			continue
		}

		buf, err := handleRequest(aMessageRequest).Deserialization()

		client.WriteString(buf)
	}
}

func main() {
	server := NewServer(9999)
	defer server.Stop()

	Println("new server success.")
	server.Start(handleConnection)
}
